package com.tts.superstar.fragment;


import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.tts.superstar.ClazzActivity;
import com.tts.superstar.Database.BookDatabase;
import com.tts.superstar.HuodongActivity;
import com.tts.superstar.MoremoActivity;
import com.tts.superstar.R;
import com.tts.superstar.ResourceActivity;
import com.tts.superstar.Tools.BitmapCache;
import com.tts.superstar.Tools.Utillity;
import com.tts.superstar.View.MyListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LiuZhiHao on 2019/4/10.
 */

public class ShouyeFragment extends Fragment {
    private static final String TAG = "ShouyeFragment";
    private RequestQueue requestQueue;
    private LinearLayout mLayoutTop;
    private LinearLayout mLayout1;
    private LinearLayout mLayout2;
    private LinearLayout mLayout3;
    private LinearLayout mLayout4;
    private LinearLayout mLayoutChangyong;
    private MyListView mListChangyong;
    private LinearLayout mLayoutTuijian;
    private MyListView mListTuijian;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<Map> list;
    private List<Map> changyongList;
    private MyAdatper changyongAdapter;
    private MyAdatper tuijianAdapter;

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shouye, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        requestQueue = Volley.newRequestQueue(getActivity());
        list = new ArrayList<>();
        changyongList = new ArrayList<>();
        swipeRefreshLayout = view.findViewById(R.id.swip_shouye);
        mLayoutTop = view.findViewById(R.id.layout_top);
        mLayout1 = view.findViewById(R.id.layout1);
        mLayout2 = view.findViewById(R.id.layout2);
        mLayout3 = view.findViewById(R.id.layout3);
        mLayout4 = view.findViewById(R.id.layout4);
        mLayoutChangyong = view.findViewById(R.id.layout_changyong);
        mListChangyong = view.findViewById(R.id.list_changyong);
        mLayoutTuijian = view.findViewById(R.id.layout_tuijian);
        mListTuijian = view.findViewById(R.id.list_tuijian);
        tuijianAdapter = new MyAdatper(R.layout.item_tuijian, list);
        changyongAdapter = new MyAdatper(R.layout.item_changyong, changyongList);
        mListTuijian.setAdapter(tuijianAdapter);
        mListChangyong.setAdapter(changyongAdapter);

        initData();
        initLisn();
        flashChangYongData();
    }

    private void initLisn() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            Thread.sleep(1000);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    flashChangYongData();
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        mLayout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ClazzActivity.class);
                startActivity(intent);
            }
        });

        mLayout2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ResourceActivity.class);
                startActivity(intent);
            }
        });

        mLayout3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), HuodongActivity.class);
                startActivity(intent);
            }
        });

        mLayout4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), MoremoActivity.class);
                startActivity(intent);
            }
        });

    }

    private void initData() {
        list.clear();
        for (int i = 1; i < 41; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("name", "贴吧表情" + i + "号");
            list.add(map);
        }
        tuijianAdapter.notifyDataSetChanged();
    }

    void flashChangYongData() {
        changyongList.clear();
        BookDatabase bookDatabase = new BookDatabase(getActivity().getApplicationContext());
        SQLiteDatabase db = bookDatabase.getReadableDatabase();
        Cursor cursor = db.rawQuery("select name,imgUrl from book", null);
        while (cursor.moveToNext()) {
            Map<String, String> map = new HashMap<>();
            map.put("name", cursor.getString(cursor.getColumnIndex("name")));
            map.put("imgUrl", cursor.getString(cursor.getColumnIndex("imgUrl")));
            changyongList.add(map);
        }
        if (cursor.getCount() != 0) {
            Log.e(TAG, "flashChangYongData: " + cursor.getCount());
            if (mLayoutChangyong.getVisibility() == View.GONE) {
                mLayoutChangyong.setVisibility(View.VISIBLE);
                mListChangyong.setVisibility(View.VISIBLE);
            }
        }
        changyongAdapter.notifyDataSetChanged();
    }

    class MyAdatper extends BaseAdapter {
        int layout;
        List<Map> list;

        public MyAdatper(int layout, List<Map> list) {
            this.layout = layout;
            this.list = list;
        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (viewHolder == null) {
                convertView = LayoutInflater.from(getActivity().getApplicationContext()).inflate(layout, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            final Map<String, String> map = list.get(position);
            viewHolder.mTextName.setText(map.get("name"));
            viewHolder.mImg.setDefaultImageResId(R.drawable.ic_launcher_background);
            viewHolder.mImg.setErrorImageResId(R.drawable.ic_launcher_background);


            if (layout == R.layout.item_changyong) {
                viewHolder.mBtnAdd.setVisibility(View.GONE);
                String url = map.get("imgUrl");
                getNetworkImg(viewHolder.mImg, url);
            } else {
                final String url = "http://120.79.156.71/file/biaoqng" + (position + 1) + ".png";
                getNetworkImg(viewHolder.mImg, url);
                viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setBtn(map, url);
                    }
                });
            }

            return convertView;
        }

        private void getNetworkImg(NetworkImageView imageView, String url) {
            ImageLoader loader = new ImageLoader(requestQueue, new BitmapCache());
            imageView.setImageUrl(url, loader);
        }


        void setBtn(Map<String, String> map, String url) {
            if (layout != R.layout.item_changyong) {
                BookDatabase bookDatabase = new BookDatabase(getActivity().getApplicationContext());
                SQLiteDatabase db = bookDatabase.getWritableDatabase();
                Cursor cursor = db.rawQuery("select name,imgUrl from book where name = ?", new String[]{map.get("name")});
                if (cursor.getCount() == 0) {
                    ContentValues values = new ContentValues();
                    values.put("name", map.get("name"));
                    values.put("imgUrl", url);
                    db.insert("book", null, values);
                    Log.d(TAG, "onClick: Add");
                    Toast.makeText(getActivity().getApplicationContext(), "已添加常用", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), "已经添加过", Toast.LENGTH_SHORT).show();
                }

            }
        }

        class ViewHolder {
            View view;
            NetworkImageView mImg;
            TextView mTextName;
            ImageButton mBtnAdd;

            ViewHolder(View view) {
                this.view = view;
                this.mImg = view.findViewById(R.id.img);
                this.mTextName = view.findViewById(R.id.text_name);
                this.mBtnAdd = view.findViewById(R.id.btn_add);
            }
        }
    }
}
